
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            Form.api.bindevent("form[role=form]");
            $(function () {
                // var a=new Array();
                // var b=new Array();
                // a.push({"pro":"测试","pc":"ces"});
                // b.push({"pro":"测试b","pc":"cesb"});
                // var c=[a,b];     
                // var d=JSON.stringify(c);
                // return false;
                $('#myModal').on('show.bs.modal', function (e) {
                    Controller.customer();
                });
                //显示客户列表
                $("#c-supplier").focus(function () {
                    $("#myModal").modal("show");
                });
                setnums();
                $('#myModal').on('hidden.bs.modal', function () {
                    $('#table1').bootstrapTable('destroy');
                });



                $('#modelProduct').on('show.bs.modal', function (e) {

                    var btn = $(e.relatedTarget)
                    Controller.getProduct(btn);
                });

                $('#modelProduct').on('hidden.bs.modal', function () {
                    $('#table2').bootstrapTable('destroy');
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        customer: function () {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/sell/index?a=1'
                }
            });

            var table = $("#table1");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'contact', title: __('Contact')},
                        {field: 'phone', title: __('Phone')},
                        {field: 'description', title: __('Description')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/sell/sell/getCustomerByid',
                                    success: function (data, ret) {
                                        $("#c-supplier").val(data.row.name);
                                        $("#c-supId").val(data.row.id);
                                        $("#c-contact").val(data.row.contact);
                                        $("#c-phone").val(data.row.phone);
                                        $("#c-address").val(data.row.address);
                                        $("#c-city").citypicker("reset");
                                        if (data.city != "") {

                                            $("#c-city").citypicker("destroy");
                                            $("#c-city").citypicker({
                                                province: data.city[0],
                                                city: data.city[1],
                                                district: data.city[2]
                                            });

                                        }
                                        $('#myModal').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: function (value, row, index) {
                                if (row.status == '禁用') {
                                    return '该客户已禁用'
                                } else {
                                    var buttons = $.extend([], this.buttons || []);
                                    return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
                                }
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        getProduct: function (btn) {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/sell/index?a=2'
                }
            });

            var table = $("#table2");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                escape: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'specification', title: __('Specification')},
                        {field: 'sku', title: __('Sku')},
                        {field: 'prop', title: __('Prop'), formatter: function (value, row, index) {
                                var str = "";
                                if (row.prop != "") {
                                    var arr = JSON.parse(row.prop);
                                    console.log(arr[0]);

                                    for (var i = 0; i < arr.length; i++) {

                                        if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                            str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
                                        }
                                    }
                                }
                                return str;
                            }}, {field: 'inventory', title: __('Inventory')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/purchase/addorder/getProductByid',
                                    success: function (data, ret) {
                                        var _this = btn.parent().parent();
                                        // alert(JSON.stringify(data.row))
                                        _this.find('.inventory').text(data.row.inventory)
                                        _this.find(".find").val(data.row.name);
                                        _this.find(".find").attr("data-id", data.row.id);
                                        _this.find(".unit").text(data.row.unit);
                                        _this.find("td:eq(1)").text(data.row.sku);
                                        _this.find("td:eq(3)").text(data.row.specification);
                                        if (data.row.prop != "") {
                                            var arr = JSON.parse(data.row.prop);
                                            var str = "";
                                            for (var i = 0; i < arr.length; i++) {
                                                if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                    str += arr[i]['title'] + ":" + arr[i]['value'] + "; <br>";
                                                }
                                            }
                                            _this.find("td:eq(4)").html(str);
                                        }
                                        $('#modelProduct').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });
            Table.api.bindevent(table);

        }

    };
    return Controller;
});
// 添加
function addRow() {
    var len = $('#table tr').length - 1;
    var lens = len - 2;
    var tempTr = '<tr>' +
            '<td>' + len + '</td>' +
            '<td></td>' +
            '<td><input  data-id="" type="text" name="" class="find" data-toggle="modal" data-target="#modelProduct" data-rule=""></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td class="unit"></td>' +
            '<td class="inventory"></td>' +
            '<td><input  type="number" name="" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
            '<td><input  type="number" data-rule="required;range(0~);" name="" onblur="calMoney(this)"  class="unit-price"></td>' +
            '<td class="subtotal"></td>' +
            '<td><textarea rows="2" class="remarks" cols="20"></textarea></td>' +
            '<td> <button type="button" class="btn btn-primary" onclick="addRow()">添加</button><button type="button" class="btn btn-default" onclick="delRow(this)" >删除</button> </td>' +
            '</tr>';
    $('#table tbody tr:eq(' + lens + ')').after(tempTr);
}
// 删除
function delRow(obj) {

    if ($('#table tbody tr').length == 2) {
        alert(__("Can't delete"));
        return false;
    }
    $(obj).parent().parent().remove();
    totalNums(null);
    calTotalMoneys()
    setnums();
}
//设置序号
function setnums() {
    var len = $('#table tr').length;
    for (var i = 1; i < len - 1; i++) {
        $('#table tr:eq(' + i + ') td:first').text(i);
    }
}

//计算总数量
function totalNums(obj) {
    var len = $('#table tr').length;
    var total = 0;
    if (obj != null) {
        calMoney(obj);
    }
    for (var i = 1; i < len - 1; i++) {
        var nums = $('#table tr:eq(' + i + ') .nums').val();
        nums = getNumValue(nums);
        if (nums == false || nums < 0) {
            total = false;
            return false;
        }
        total += nums;
    }
    if (total != false) {
        $(".totalnums").text(total);
        $("#allNums").val(total);
    }
}

function getNumValue(num) {
    if (!isNaN(num) && num != "") {
        num = parseFloat(num);
        var a = isPositiveInteger(num)
        if (a == false) {
            num = false;
        }
    } else {
        num = false;
    }
    return num;
}

function isInteger(obj) {
    return obj % 1 === 0
}

function isPositiveInteger(s) {//是否为正整数
    var re = /^[0-9]+$/;
    return re.test(s)
}
// 小计
function calMoney(obj) {
    var total = 0;
    var nums = $(obj).parent().parent().find(".nums").val();
    var nuitprice = $(obj).parent().parent().find(".unit-price").val();
    if (nuitprice == "") {
        return false;
    }
    nuitprice = parseFloat(nuitprice);
    nums = getNumValue(nums);
    if (nums == false) {
        return false;
    }
    total = nuitprice * nums;
    total = total.toFixed(2);
    $(obj).parent().parent().find(".subtotal").text(total);
    calTotalMoneys();
}
// 计算总金额
function calTotalMoneys() {
    var len = $('#table tr').length;
    var total = 0;
    for (var b = 1; b < len - 1; b++) {
        var str = '#table tr:eq(' + b + ') .subtotal';
        var a = $(str).text();
        if (a == "") {
            a = 0;
        }
        a = parseFloat(a);
        if (a == "NaN" || a == "" || a == undefined) {
            a = 0;
        }
        total += a;
    }
    $("#table #allMoney").text(total);
    var rate = $("#c-rate").val();
    rate = parseFloat(rate);
    var totalMoney = total * (1 + rate / 100);
    // var totalMoney=total;
    $("#money").val(total);
    totalMoney = totalMoney.toFixed(2);
    $("#totalMoney").text(totalMoney);
    $("#totalMoneys").val(totalMoney);

}

function submitData() {
    var data = $("#add-form").serialize();
    // console.log(data)
    if ($("#c-supId").val() == '') {
        Toastr.error(__("Please select a merchant"));
        return false;
    }
    if ($("#hose-fist").val() == 0) {
        Toastr.error(__("Please select a warehouse"));
        return false;
    }
    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {
                var id = $("#table tr:eq(" + i + ")").find('.find').attr("data-id");
                if (id == "") {
                    Toastr.error(__("Please select a product"));
                    return false;
                }
                //判断购买数量是否大于库存 start
                var inventory = $("#table tr:eq(" + i + ")").find('.inventory').text()  //当前行的商品库存
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val();  //当前行的购买数量
                if (parseInt(nums) > parseInt(inventory)) {
                    alert('购买数量不能大于当前库存(序号' + i + '产品)');
                    return
                }
                //判断购买数量是否大于库存 end
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var b = i - 1;
                arr.push({"product_id": id, "price": unitPrice, "nums": nums, "subtotal": subtotal, "unit": unit, "remarks": remarks});
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            // data.push({"name":"row['product']","value":temp});
            // var resutlData=JSON.stringify(data);
            // console.log(resutlData)
            Fast.api.ajax({
                url: 'ykjp/sell/sell/addSell',
                data: resutlData
            }, function (data, ret) {
                //成功的回调

                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.reload();
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                // alert(ret.msg);
                return false;
            });
        }
    })

}
